package com.oppo.controller;

import com.oppo.result.BusinessResult;
import com.oppo.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传下载预览控制层
 *
 * @author steve
 * @since 2022-01-29 20:06
 */

@Api(value = "文件上传下载",tags = "文件上传下载")
@RestController
@RequestMapping(value = "/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @ApiOperation(value = "上传文件方法1")
    @PostMapping(value = "/upload1")
    public BusinessResult<String> upload(@RequestPart("file") MultipartFile file) {
        try {
            return BusinessResult.success(fileService.upload(file));
        } catch (Exception e) {
            return BusinessResult.fail("文件上传失败");
        }
    }

    @ApiOperation(value = "上传文件方法2")
    @PostMapping(value = "/upload-file")
    public BusinessResult<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            return BusinessResult.success(fileService.uploadFile(file));
        } catch (Exception e) {
            return BusinessResult.fail("文件上传失败");
        }
    }


    @ApiOperation(value = "下载文件")
    @GetMapping(value = "/download")
    public ResponseEntity download() throws Exception {
        // todo 这里应从数据库查出字段拼接成
        String fileName = "d:\\ig.png";
        FileSystemResource file = new FileSystemResource(fileName);
        HttpHeaders headers = new HttpHeaders();
        String downFileName = "123.png";
        headers.add("Content-Disposition", "attachment; filename=" + downFileName);
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.contentLength())
                // 这个属性表示响应的内容是通过字节流的方式进行传输的
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }

    // 江南一点雨代码
    // B站：https://www.bilibili.com/video/BV1ei4y1M7Kf/?spm_id_from=333.788.recommend_more_video.-1
    // GitHub:https://github1s.com/lenve/javaboy-code-samples/blob/master/fileupload/pom.xml#L27-L37

    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
    @ApiOperation(value = "上传文件-江南一点雨")
    @PostMapping("/upload")
    public Map<String,Object> fileupload(@RequestPart("file") MultipartFile file, HttpServletRequest req) {
        Map<String, Object> result = new HashMap<>();
        String format = sdf.format(new Date());
        // 获取项目运行的当前路径
        String realPath = req.getServletContext().getRealPath("/") + format;
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        try {
            file.transferTo(new File(folder, newName));
            String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + format + newName;
            result.put("status", "OK");
            result.put("name", oldName);
            result.put("url", url);
        } catch (IOException e) {
            result.put("status", "ERROR");
            result.put("msg", e.getMessage());
        }
        return result;
    }

}
